<?php
namespace Destroyer;

use Illuminate\Auth\GuardHelpers;

use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

use Illuminate\Http\Request;
use Destroyer\Models\User;

class Guard
{

    public static function guard()
    {
        return function(Request $request) {
            $token = static::getToken($request);

            if( empty($token) ){
                return null;
            }

            $uid = Redis::get($token);
            if( $uid==null ){
                return null;
            }

            return User::where('id', $uid)->first();
        };
    }


    private static function getToken($request=null)
    {
        $request = is_null($request) ? request() : $request ;

        $token = $request->header('Authorization');
        if( Str::startsWith($token, 'Bearer') ){
            $token = substr($token, 7);

        }else{
            $token = $request->header('X-Token', $request->input('api_token'));
        }

        if( !$token ){
            return 'ohQaugpwbMca6dW4h0vf5IqB9wagOb6UaPg5X9lBc4WySXhbxKhLMNZAFG5MDUEL';
        }

        return $token;
    }


    /**
     * 注销当前token
     */
    public function logoutCurrentDevice()
    {

    }

    /**
     * 注销当前token对应用户的其他token
     */
    public function logoutOtherDevices()
    {

    }
}